<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;

// 使用类

use App\Http\Controllers\Controller;
use Illuminate\Contracts\Validation\Validator;
// 后台商品控制器
class GoodsController extends Controller
{
    // 商品首页

    public function index(Request $request){

        $count = $request -> input('count',10);
        $search = $request -> input('search','');
        $request = $request -> all();
          // 查询数据并分页
         $data = \DB::table('goods')
                    ->join('goodsdetails', 'goodsdetails.gid', '=', 'goods.id')
                    ->join('types', 'types.id', '=', 'goods.tid')
                    ->where("goods.goodsname",'like','%'.$search.'%')
                    ->select('goods.*', 'goodsdetails.num','types.typename','types.path')
                    ->paginate($count);

        // 处理小图

        foreach ($data as $key => $value) {
            # code...

            $value['tupian']=\DB::table("goodsimg")->where("gid",$value['id'])->get();

        }
        // dd($value);


       // dd($data);
        // 加载页面

       return view("admin.goods.index")->with("data",$data)->with('request',$request);

    }

    // 商品的添加页面

    public function create(){

        // 查询分类

        $data=\DB::select("select types.*,concat(path,id) p from types order by p");

         foreach ($data as $key => $value) {
            // 统计一个字符串在另一个字符串出现次数
            $len = substr_count($value['path'],',');

             // 通过， 判断是几级分类
              if($len==1){
                $data[$key]['typename'] = $value['typename'];
              }else{
                $data[$key]['typename'] = str_repeat('|----',$len-1).$value['typename'];
              }

        }

        // 加载添加页面

       return view('admin.goods.create')->with("data",$data);
    }

    // 处理商品的插入操作

    public function store(Request $request){
        // 获取多图

        //echo 1;
        $imgs=$request->input("imgs");

        //商品详情
        $text=$request->input("text");
        //商品配置
        $config=$request->input("config");
        //商品库存
        $num=$request->input("num");

        //分类id
        $tid=$request->input("tid");

        // 移除不需要的字符

        $data=$request->except("_token","imgs","text","config","num","img");


        $rules = [
            'tid'=>'required',
            'goodsname'=>'required',
            'title'=>'required',
            'price'=>'required',
            'imgs'=>'required',
            'img'=>'required',
        ];

        $message = [
            'tid.required'=>'请选择类别',
            'goodsname.required'=>'请输入商品名称',
            'title.required'=>'请输入商品标题',
            'price.required'=>'请输入商品价格',
            'imgs.required'=>'请上传商品封面',
            'img.required'=>'请上传商品多图',
        ];

       $this->validate($request,$rules,$message);


        //拼接图片路径
         $filename=$request['img'];

         // 文件路径
         $temp_path = '/Uploads/goods';
         $img = ltrim($temp_path.'/'.$filename);
         $data['img']=$img;

        $data['addtime']=time();
        $data['goodscode']="SP_".time().rand();


      // dd($data);
        // // 插入数据库

        if ($id=\DB::table("goods")->insertGetId($data)) {
            //添加商品详情
            $info=array();

            $info['gid']=$id;
            $info['text']=$text;
            $info['num']=$num;
            $info['config']=$config;

            \DB::table("goodsdetails")->insert($info);

            // 处理商品多图片
            $arr=explode(',', $imgs);



            foreach ($arr as $key => $value) {
                $brr=array();

                //获取id
                $brr['gid']=$id;

                //拼接多图路径
                $filename=$value;

                 // 文件路径
                 $temp_path = '/Uploads/goods';
                 $img = ltrim($temp_path.'/'.$filename);
                 $brr['imgs']=$img;
                 //var_dump($brr);
                \DB::table("goodsimg")->insert($brr);
            }

            return redirect('admin/goods');
        }
        else{
            return back();
        }
    }


     /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edi($id,$tid)
    {

     // 查询数据库
     $data = \DB::table('goods')
                ->join('goodsdetails', 'goodsdetails.gid', '=', 'goods.id')
                ->where("goods.id",$id)
                ->first();
    //把小图也查到
    $tupian=\DB::table("goodsimg")->where("gid",$id)->get();
    //查询分类
    //拼接path ID 查询
     $types =\DB::table('types')
                 ->select(\DB::raw('*,concat(path,id) as p'))
                 ->where('id',$tid)
                 ->first();

        // 统计一个字符串在另一个字符串出现次数
        $len = substr_count($types['path'],',');

         // 重复的使用一个字符串
          if($len==1){
            $types['typename'] = $types['typename'];
          }else{
            $types['typename'] = str_repeat('|----',$len-1).$types['typename'];
          }

  // dd($tupian);
        //分配数据
      return view('admin.goods.edit')->with("data",$data)->with('types',$types)->with('tupian',$tupian);
    }





    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request,$id)
    {

        //商品表数据
        $data=$request->except("_token","_method","img","imgs","num","config","text");

        //商品详细数据
        $details['num']=$request->input('num');
        $details['config']=$request->input('config');
        $details['text']=$request->input('text');


       //   $rules = [
       //      'tid'=>'required',
       //      'goodsname'=>'required',
       //      'title'=>'required',
       //      'price'=>'required',
       //  ];

       //  $message = [
       //      'goodsname.required'=>'请输入商品名称',
       //      'title.required'=>'请输入商品标题',
       //      'price.required'=>'请输入商品价格',
       //  ];

       // $this->validate($request,$rules,$message);



        //获取上传商品封面图片名称
        $filename=$request['img'];

        //获取上传商品小图图片名称 数组
        $goodsimg=$request->input('imgs');

        if(!empty($goodsimg)){

         $arr=explode(',', $goodsimg);

        }

        //对比
        $reg=\DB::table("goods")->where('id','=',$id)->first();
        //获取原有小图
        $regs=\DB::table("goodsimg")->where('gid','=',$id)->get();

        if($data['goodsname']==$reg['goodsname']){
            unset($data['goodsname']);
        }



            if(!empty($filename)){

                     // 文件路径
                     $temp_path = '/Uploads/goods';
                     $img = ltrim($temp_path.'/'.$filename);
                     $data['img']=$img;

                    //删除原有文件
                     $filePath=$reg['img'];
                    $re = \Storage::disk('public')->delete($filePath);
            }


            if(!empty($goodsimg)){

                    //删除原有图片
                     foreach ($regs as $kk => $vv) {
                         # code...
                        //删除原有文件
                       $filePath = $vv['imgs'];
                        $re2 = \Storage::disk('public')->delete($filePath);
                     }

                    \DB::table('goodsimg')->where('gid',$id)->delete();

                 foreach ($arr as $key => $value) {
                        $dataimg=array();

                        //获取id
                        $dataimg['gid']=$id;

                        //拼接多图路径
                        $filename=$value;

                         // 文件路径
                         $temp_path = '/Uploads/goods';
                         $imgs = ltrim($temp_path.'/'.$filename);
                         $dataimg['imgs']=$imgs;

                           //修改商品小图
                       $res3=\DB::table("goodsimg")->insert($dataimg);

                }


            }


       $res= \DB::table("goods")->where('id',$id)->update($data);
       $res2=\DB::table("goodsdetails")->where('gid',$id)->update($details);


       if($res || $res2 || $res3){

             return redirect('admin/goods')->with('success','修改成功');

         }else{

             return back()->with('error','修改失败');
        }


    }




     /**
     * 获取标签
     *
     * @param
     * @return \Illuminate\Http\Response
     */

    public function Attrs(Request $request)
    {


     $arr=$request->except('_token','_method');
     $data=\DB::table('tag')->where('tid',$arr['tid'])->get();


        if ($data) {
            # code...
            echo json_encode($data);
        }else{
            echo 0;
         }
    }



    /**
     * 修改上下架的方法
     *
     * @param
     * @return \Illuminate\Http\Response
     */

    public function ajaxSale(Request $request)
    {

        $arr=$request->except('_token');
    // dd($arr);
        if (\DB::update("update goods set is_on_sale= $arr[is_on_sale] where id=$arr[id]")) {
            # code...
            echo 1;
        }else{
            echo 0;
         }
    }



     /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //

         //查找这个图片
        $reg=\DB::table("goods")->where('id',$id)->first();
        // //  //删除原有文件
         $filePath=$reg['img'];
        //  dd($reg);

         //删除goods
         $res=\DB::table("goods")->delete($id);

         //删除图片
         $re = \Storage::disk('public')->delete($filePath);

         //删除商品详情
        $res=\DB::table("goodsdetails")->where('gid',$id)->delete();

         //查询商品小图片  删除
         $imgs=\DB::table("goodsimg")->where('gid',$id)->get();

            foreach($imgs as $v ){

                $file=$v['imgs'];
                $reg=\Storage::disk('public')->delete($file);
            }
        //删除数据库小图
        $reimg=\DB::table("goodsimg")->where('gid',$id)->delete();
        if ($res && $re && $reimg) {

            return "1";
        }else{
            return 0;
        }
    }

}
